rm(list=ls())
library(tidyverse)

# Function to create datase with observations per muncode-year and time-variable columns 
center <-function(df,year_center){
  df <- df %>% 
    mutate(center = year - year_center) %>% 
    select(-year) %>%
    filter(between(center,-3,4)) %>% 
    mutate(center = str_replace(ifelse(center<0,paste0("t_minus",center),paste0("t_plus",center)),"-",""),
           center = str_replace(center,"t_plus0","t_0")) %>% 
    gather(variable, value, -c(mun_code,center)) %>%  
    unite(center,variable,center) %>%
    spread(center,value) %>% 
    mutate(year = year_center) 
  return(df)
}


#Reads CSV Files from Violence Indicatores - obtained at: https://www.ipea.gov.br/atlasviolencia/filtros-series/1/homicidios

violence_indicators <- read_delim(here::here("data","raw","violence","taxa-homicidios.csv"),
                                  delim = ";",
                                  skip = 1,
                                 col_names = c("mun_code","mun_name","year","homicide_rate"),
                                 col_types = "ccdd",
                                 local = locale(encoding = "latin1"))

#Process files 
violence_indicators <- violence_indicators %>% 
  mutate(mun_code = str_sub(mun_code,1,-2)) %>% 
  select(-mun_name)

# Center violence outcomes

violence_outcomes <-  map(seq(2000,2012, by = 4), center, df = violence_indicators) %>%
  bind_rows() %>% 
  select(mun_code,year, everything()) %>%  
  mutate_at(vars(matches("_t_")),
            .funs = funs(as.numeric(.)))

#Save

write_rds(x = violence_outcomes,path = here::here("data","processed","welfare_outcomes","violence_outcomes.rds"))


